﻿using Microsoft.ML;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using TensorFlow_ImageClassification;

namespace TensorFlow_ImageClassification_WinForm
{
    public partial class Form1 : Form
    {
        private readonly string imageClassifierZip;
        private string pathname = string.Empty;

        public Form1()
        {
            InitializeComponent();

            imageClassifierZip = Path.Combine("../../../../MLModel/TensorFlow_ImageClassification", "imageClassifier.zip");
        }
        

        private void Button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog
            {
                InitialDirectory = ".",
                Filter = "所有文件(*.*)|*.*"
            };
            file.ShowDialog();

            if (file.FileName != string.Empty)
            {
                try
                {
                    pathname = file.FileName;
                    this.pictureBox1.Load(pathname);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            MLContext mlContext = new MLContext(seed: 1);
            // Load the model
            ITransformer loadedModel = mlContext.Model.Load(imageClassifierZip, out _);

            // Make prediction function (input = ImageNetData, output = ImageNetPrediction)
            var predictor = mlContext.Model.CreatePredictionEngine<ImageNetData, ImageNetPrediction>(loadedModel);

            ImageNetData image = new ImageNetData
            {
                ImagePath = pathname
            };
            var pred = predictor.Predict(image);
            this.label2.Text = pred.PredictedLabelValue;
        }
    }
}
